package com.halflife.comeElectricity.orderMng.order;

import com.halflife.framework.dto.Result;
import com.halflife.framework.exception.BusinessException;
import com.halflife.framework.utils.Utils;
import com.halflife.comeElectricity.admin.NavStatic;
import com.halflife.comeElectricity.member.rider.Rider;
import com.halflife.comeElectricity.member.rider.RiderStatus;
import com.halflife.comeElectricity.orderMng.order.dto.OrderDTO;
import com.halflife.comeElectricity.orderMng.order.vo.OrderVO;
import com.halflife.message.OrderMessage;
import com.halflife.message.OrderMessageRepository;
import com.halflife.shiro.utils.ShiroUtil;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Rectangle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhaoyf on 2018/2/12.
 */
@RestController
@RequestMapping("/rider_order")
public class OrderRiderController {
    private Logger logger = LoggerFactory.getLogger(OrderRiderController.class);
    @Resource
    private OrderService orderService;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderExtRepository orderExtRepository;
    @Resource
    private OrderMessageRepository orderMessageRepository;
    //
    @PostMapping("/add")
    @ResponseStatus(HttpStatus.CREATED)
    public void add(@RequestBody OrderDTO orderDTO, HttpServletRequest request)throws Exception{
        Order order = new Order();
        OrderExt orderExt = new OrderExt();
        orderDTO.convert(order,orderExt);
        orderService.add(order,orderExt);

    }
    @GetMapping("/{id}")
    public ResponseEntity<OrderExt> get(@PathVariable Integer id, HttpServletRequest request){
        Order order = orderRepository.selectByPrimaryKey(id);
        OrderExt orderExt = orderExtRepository.selectByPrimaryKey(id);
        return new ResponseEntity<OrderExt>(orderExt, HttpStatus.OK);

    }
    @GetMapping("/vo/{id}")
    public ResponseEntity<OrderVO> getVObyId(@PathVariable Integer id, HttpServletRequest request){
        Rider rider = ShiroUtil.getRider(request);
        if (rider == null) {
            throw new BusinessException("您没有登陆,请退出系统重新登陆");
        }
        OrderVO orderExt = orderExtRepository.selectVOById(id);
        if (orderExt == null) {
            return new ResponseEntity<OrderVO>(HttpStatus.NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("riderId", rider.getId());
        map.put("status",OrderEnum.WAITTOGET.m_orderStatus.byteValue());
        map.put("currentPage",0);
        map.put("pageSize",10);
        List<Order> orders = orderRepository.selectOrders(map);
        Order temp = new Order();
        temp.setGoodTypeId(orderExt.getGoodsType().getId());
        orders.add(temp);
        int hj = 0;
        for (Order order : orders) {
            switch (order.getGoodTypeId()){
                case 1:
                    hj+=this.item1;
                    break;
                case 2:
                    hj+=this.item2;
                    break;
                case 3:
                    hj+=this.item1;
                    break;
            }
        }
        if(hj>this.score){
            orderExt.setGrabStatus(Byte.valueOf("1"));
        }
        orderExt.setGrabStatus(Byte.valueOf("0"));
        return new ResponseEntity<OrderVO>(orderExt, HttpStatus.OK);

    }
    @PutMapping("/updateStatus/{orderId}")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity updateOrderStatus(@PathVariable Integer orderId, HttpServletRequest request) {

        Order o = this.orderRepository.selectByPrimaryKey(orderId);
        if (o != null) {
            // OrderEnum n = OrderEnum.getStatus(2);
            o.setStatus(OrderEnum.BACKING.m_orderStatus.byteValue());
            //记录出发时间
            OrderExt e = orderExtRepository.selectByPrimaryKey(o.getId());
            e.setStartOffTime(Calendar.getInstance().getTimeInMillis());
            this.orderExtRepository.updateByPrimaryKey(e);
            if(e!=null){

                //插入消息
                OrderMessage orderMessage = new OrderMessage();
                orderMessage.setMerchantId(o.getMerchantId());
                orderMessage.setStatus(OrderMessage.STATUS_NORMAL);
                orderMessage.setMemo("您于" + NavStatic.getDate(o.getCreateTime()) + "下的订单,接单骑手已经确认回单.");
                orderMessage.setSpare("您于" + NavStatic.getDate(o.getCreateTime()) + "下的订单,接单骑手已经确认回单.");
                orderMessageRepository.insert(orderMessage);
            }
        }
        this.orderRepository.updateByPrimaryKey(o);
        return new ResponseEntity(1, HttpStatus.OK);
    }

    @GetMapping("/test/{id}")
    public Result test(@PathVariable Integer id, HttpServletRequest request){
        Rider rider = ShiroUtil.getRider(request);
        if (rider == null) {
            return Result.Error("您没有登陆,请退出系统重新登陆");
        }
        OrderVO orderExt = orderExtRepository.selectVOById(id);
        ExecutorService executor = Executors.newFixedThreadPool(20);
        for(int i=0;i<100;i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    orderService.grabOrder(rider,id);
                }
            });
        }


        return Result.Ok();

    }
    @Value("${system.rider.max_score}")
    private Integer score;
     @Value("${system.rider.max_items1}")
    private Integer item1;
     @Value("${system.rider.max_items2}")
    private Integer item2;
     @Value("${system.rider.max_items3}")
    private Integer item3;
    @PostMapping("/grab/{id}")
    public Result grabOrder(@PathVariable Integer id, HttpServletRequest request){
        Rider rider = ShiroUtil.getRider(request);
        if (rider == null) {
            return Result.Error("您没有登陆,请退出系统重新登陆");
        }
        try {
            orderService.grabOrder(rider, id);
        } catch (BusinessException e) {
            return Result.Error(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return Result.Error("未知异常!");
        }
        return Result.Ok();

    }
    @Value("${system.rider.max_items}")
    public String items;
    @Value("${system.rider.nogeo}")
    public String nogeo;
    @Value("${system.rider.max_distance}")
    public String distance;
    @Value("${system.order.timeout}")
    public Integer order_timeout;

    //获取订单管理列表 edit by liuj3
    @GetMapping("/grablist")
    public ResponseEntity<List<Order>> grablist(@RequestParam(value="id", required = false) Integer id,
                                                @RequestParam(value="longitude", required = false) Double longitude,
                                                @RequestParam(value="latitude", required = false) Double latitude,
                                                @RequestParam(value="currentPage",defaultValue = "1") Integer currentPage,
                                                @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize,
                                                HttpServletRequest request){
        logger.debug(longitude+"");
        logger.debug(latitude+"");
        logger.debug(latitude+"=========================================333333333333333333");
        Rider rider  =  ShiroUtil.getRider(request);
        List<Order> list = new ArrayList<>();
        if(rider.getState()== RiderStatus.CANCEL.getValue()){
            return new ResponseEntity<List<Order>>(list, HttpStatus.OK);
        }
        HashMap<String, Object> param = new HashMap();
        if (longitude != null) {

            Rectangle rectangle = Utils.disance(longitude, latitude, Integer.valueOf(this.distance));
            System.out.println(rectangle.getMinX() + "-" + rectangle.getMaxX());// 经度范围
            System.out.println(rectangle.getMinY() + "-" + rectangle.getMaxY());// 纬度范围

            param.put("max_lng", rectangle.getMaxX());
            param.put("min_lng", rectangle.getMinX());
            param.put("max_lat", rectangle.getMaxY());
            param.put("min_lat", rectangle.getMinY());

            param.put("longitude",longitude);
            param.put("latitude",latitude);
            param.put("currentPage", (currentPage-1)*pageSize);
            param.put("pageSize", pageSize);
        }
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE,0-order_timeout);
        param.put("time_out", now.getTimeInMillis());
        param.put("status",OrderEnum.WAITTOGET.m_orderStatus.byteValue());
        param.put("currentPage",0);
        param.put("pageSize",Integer.valueOf(this.items));

//        int totalCount = orderRepository.selectCountOrders(param);
//        //创建返回对象
//        OrderCallBack  b = new OrderCallBack();
//        //推送订单列表
////        b.setList(list);
//        //计算总页数
//        int totalPage = totalCount/pageSize;
//        if(totalCount%pageSize!= 0)
//            totalPage++;
//        b.setTotalPage(totalPage);

        list = orderRepository.selectOrders(param);
        return new ResponseEntity<List<Order>>(list, HttpStatus.OK);
    }



    @GetMapping("/list")
    // public ResponseEntity<List<CancelOrder>> list(@RequestParam(value="id",defaultValue = "null") Integer id,
    public ResponseEntity<OrderCallBack> list(@RequestParam(value="longitude", required = false) Integer longitude,
                                              @RequestParam(value="latitude", required = false) Integer latitude,
                                              @RequestParam(value="currentPage",defaultValue = "1") Integer currentPage,
                                              @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize,
                                              HttpServletRequest request){
        //oper 分页类型 0-进行中订单 1-已完成订单 -1-已取消订单
        Rider rider  =  ShiroUtil.getRider(request);
        if (longitude != null && latitude != null) {
            int radius =1;//千米
            SpatialContext geo = SpatialContext.GEO;
            Rectangle rectangle = geo.getDistCalc().calcBoxByDistFromPt(
                    geo.makePoint(longitude, latitude), radius * DistanceUtils.KM_TO_DEG, geo, null);
            System.out.println(rectangle.getMinX() + "-" + rectangle.getMaxX());// 经度范围
            System.out.println(rectangle.getMinY() + "-" + rectangle.getMaxY());// 纬度范围
        }
        //推送分页Map参数
        HashMap<String, Object> param = new HashMap();
        param.put("currentPage", (currentPage-1)*pageSize);
        param.put("pageSize", pageSize);
        param.put("riderId", rider.getId());
        int totalCount = orderRepository.selectCountOrderByPage(param);
        List<Order> list = orderRepository.selectOrderByPage(param);
        //创建返回对象
        OrderCallBack  b = new OrderCallBack();
        //推送订单列表
        b.setList(list);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        b.setTotalPage(totalPage);
        return new ResponseEntity<OrderCallBack>(b, HttpStatus.OK);
    }


    @DeleteMapping("/{id}")
    private Result deleteById(@PathVariable Integer id) {
        try {
            orderRepository.deleteByPrimaryKey(id);
            return Result.Ok();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return Result.No("系统异常");
        }
    }



}
